package com.traffic.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.traffic.constant.Status;

import com.traffic.entity.ReturnFriend;
import com.traffic.entity.UserInfo;
import com.traffic.mapper.UserInfoMapper;
import com.traffic.model.FriendResult;
import com.traffic.model.newFriendResult;
import com.traffic.service.ResourceService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.traffic.entity.Friend;
import com.traffic.mapper.FriendMapper;
import com.traffic.service.FriendService;
import java.util.*;

@Service
public class FriendServiceImpl extends ServiceImpl<FriendMapper, Friend> implements FriendService{

    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ResourceService resourceService;

    public static Integer APPLY_TAG = 0;
    public static Integer ACCEPT_TAG = 1;
    public static Integer REFUSE_TAG = 2;
    public static Integer NOT_F = 3;

    /**
     * 发起好友请求
     * @param userId
     * @param targetId
     * @return
     */
    @Override
    public Boolean apply(Long userId, Long targetId) {
        if (userId.equals(targetId)) {
            return false;
        }

        // 检查是否有记录
        QueryWrapper<Friend> wrapperL = new QueryWrapper<>();
        wrapperL.eq("user_id", userId).eq("target_id", targetId);
        Friend friendL = friendMapper.selectOne(wrapperL);
        if (ObjectUtil.isNotNull(friendL)) {
            return false;
        }
        QueryWrapper<Friend> wrapperR = new QueryWrapper<>();
        wrapperR.eq("user_id", targetId).eq("target_id", userId);
        Friend friendR = friendMapper.selectOne(wrapperR);
        if (ObjectUtil.isNotNull(friendR)) {
            return false;
        }


        Friend friend = Friend.builder().userId(userId).targetId(targetId).status(APPLY_TAG).build();
        Integer result = friendMapper.insert(friend);
        if (result > 0) {
            return true;
        }
        return false;
    }

    /**
     * 接受好友申请
     * @param id friend表记录的id
     * @return
     */
    @Override
    public Boolean accept(Long id) {
        return getBoolean(id, ACCEPT_TAG);
    }

    /**
     * 拒绝好友申请
     * @param id friend表记录的id
     * @return
     */
    @Override
    public Boolean refuse(Long id) {
        return getBoolean(id, REFUSE_TAG);
    }

    /**
     * 删除好友
     * @param userId
     * @param targetId
     * @return
     */
    @Override
    public Boolean delete(Long userId, Long targetId) {
        Friend friend = new Friend();
        QueryWrapper<Friend> wrapperL = new QueryWrapper<>();
        wrapperL.eq("user_id", userId).eq("target_id", targetId);
        Friend friendL = friendMapper.selectOne(wrapperL);
        if (ObjectUtil.isNotNull(friendL)) {
            friend = friendL;
        }else {
            QueryWrapper<Friend> wrapperR = new QueryWrapper<>();
            wrapperR.eq("user_id", targetId).eq("target_id", userId);
            Friend friendR = friendMapper.selectOne(wrapperR);
            if (ObjectUtil.isNotNull(friendR)) {
                friend = friendR;
            }else {
                return false;
            }
        }

        friend.setStatus(NOT_F);
        int result = friendMapper.updateById(friend);
        if (result > 0) {
            return true;
        }else {
            return false;
        }
    }

    /**
     * 抽取的方法
     * @param id
     * @param refuseTag
     * @return
     */
    private Boolean getBoolean(Long id, Integer refuseTag) {
        Friend friend = friendMapper.selectById(id);
        if (ObjectUtil.isNotNull(friend)) {
            friend.setStatus(refuseTag);
            int result = friendMapper.updateById(friend);
            if (result > 0) {
                return true;
            }else {
                return false;
            }
        }
        return false;
    }

    /**
     * 获取申请信息
     */
    @Override
    public List<newFriendResult> getInfoList(Long userId) {
        QueryWrapper<Friend> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).or().eq("target_id", userId);
        List<Friend> friendList = new ArrayList<>();
        friendList = friendMapper.selectList(wrapper);

        List<newFriendResult> results = new ArrayList<>();
//        for (Friend friend:friendList) {
//            FriendResult result = new FriendResult();
//
//            result.setFriend(friend);
//            result.setUser(get(friend.getUserId()));
//            result.setTarget(get(friend.getTargetId()));
//            results.add(result);
//        }
        for (Friend friend:friendList) {
            newFriendResult result = new newFriendResult();

            result.setFriend(friend);
            result.setUser(getRfriend(friend.getUserId()));
            result.setTarget(getRfriend(friend.getTargetId()));
            results.add(result);
        }

        return results;
    }

    /**
     * 获取好友列表
     * @param userId
     * @return 返回的 好友列表的好友 id 头像 nickname
     */
    @Override
    public List<ReturnFriend> getFriendList(Long userId) {
        QueryWrapper<Friend> wrapper = new QueryWrapper<>();
        wrapper.eq("status", ACCEPT_TAG);
        wrapper.eq("user_id", userId).or().eq("target_id", userId);
        List<Friend> friendList = new ArrayList<>();
        friendList = friendMapper.selectList(wrapper);
        List<UserInfo> userInfos = new ArrayList<>();
        List<ReturnFriend> returnFriends = new ArrayList<>();
        for (Friend friend : friendList) {
            Long id = friend.getUserId();
            if (id.equals(userId)) {
                id = friend.getTargetId();
            }
            userInfos.add(get(id));
        }

        for (UserInfo useri:userInfos) {
            ReturnFriend r= new ReturnFriend();

            r.setUserId(useri.getUserId());
            r.setId(useri.getId());

            r.setNickName(useri.getNickName());

            r.setHeadImg(resourceService.getImgUrl(useri.getHeadImg()));
            returnFriends.add(r);

        }


        return returnFriends;
    }

    /**
     * 获取部分用户信息
     * @param id
     * @return
     */
    UserInfo get(Long id) {
        UserInfo temp = userInfoMapper.selectById(id);
        if (ObjectUtil.isNotNull(temp)) {
            UserInfo userInfo = UserInfo.builder().userId(temp.getUserId()).headImg(temp.getHeadImg()).nickName(temp.getNickName()).build();
            return userInfo;
        }
        return null;
    }

    ReturnFriend getRfriend(Long id) {
        UserInfo temp = userInfoMapper.selectById(id);
        if (ObjectUtil.isNotNull(temp)) {
            String headimgurl = resourceService.getImgUrl(temp.getHeadImg());
            ReturnFriend returnFriend = ReturnFriend.builder().userId(temp.getUserId()).headImg(headimgurl).nickName(temp.getNickName()).build();
            return returnFriend;
        }
        return null;
    }

    /**
     * 是否为好友
     * @param userId targetId
     * @return
     */
    @Override
    public Integer isFriend(Long userId, Long targetId) {

        QueryWrapper<Friend> wrapper = new QueryWrapper<>();

        QueryWrapper<Friend> wrapper2 = new QueryWrapper<>();

        Object status1 = friendMapper.selectObjs(wrapper.select("status").eq("user_id",userId).eq("target_id",targetId));

        if (ObjectUtils.isEmpty(status1)){
            Object status2 = friendMapper.selectObjs(wrapper2.select("status").eq("user_id",targetId).eq("target_id",userId));
            if (ObjectUtils.isEmpty(status2)){
                return 3;
            }else{
                return Integer.parseInt(StringUtils.strip(status2.toString(),"[]"));
            }
        }
        String protectstring = StringUtils.strip(status1.toString(),"[]");
        if (protectstring.contains("1"))return 1;
        else return 0;

    }

    @Override
    public List<Long> getFriend(Long userId) {
        QueryWrapper<Friend> wrapper = new QueryWrapper<>();

        List<Object> t1 = friendMapper.selectObjs(wrapper.select("target_id").eq("user_id",userId).eq("status",1));

        QueryWrapper<Friend> wrapper2 = new QueryWrapper<>();
        List<Object> t2 = friendMapper.selectObjs(wrapper2.select("user_id").eq("target_id",userId).eq("status",1));

        List<Long>l1 = new ArrayList<>();
        List<Long>l2 = new ArrayList<>();

        for (Object id: t1) {
            Long temp = Long.parseLong(id.toString());
            l1.add(temp);
        }

        for (Object id: t2) {
            Long temp = Long.parseLong(id.toString());
            l2.add(temp);
        }


        Set<Long> set = new HashSet<>(l1);
        set.addAll(l2);
        List<Long> list = new ArrayList<>(set);


        return list;
    }



}
